<?php

namespace app\controller;

use support\Request;
use support\Response;
use app\service\SettlementStrategyService;
use app\model\RoomSettlement;

class SettlementStrategyController
{
    /**
     * 生成用户净结算策略
     */
    public function generateUserStrategy(Request $request): Response
    {
        $userId = $request->get('user_id');
        $roomId = $request->get('room_id');
        
        error_log("生成用户结算策略请求: user_id={$userId}, room_id={$roomId}");
        
        if (!$userId || !$roomId) {
            return json(['success' => false, 'message' => '用户ID和房间ID不能为空']);
        }

        try {
            // 检查房间状态
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }
            
            if ($room->status === 'finished') {
                return json(['success' => false, 'message' => '房间已结算，无法生成结算策略']);
            }
            
            // 检查用户在房间中的状态
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();
                
            if (!$roomUser) {
                return json(['success' => false, 'message' => '用户不在该房间中']);
            }
            
            if ($roomUser->status === \app\model\RoomUser::STATUS_FINISHED) {
                return json(['success' => false, 'message' => '您在该房间的结算已完成，无法重新生成结算策略']);
            }
            
            // 检查是否已经生成过策略
            if (\app\model\RoomSettlementDetail::hasUserGeneratedStrategy($userId, $roomId)) {
                return json(['success' => false, 'message' => '您已生成过结算策略，如需修改请重新生成']);
            }
            
            $strategy = SettlementStrategyService::generateUserSettlementStrategy($userId, $roomId);
            
            error_log("结算策略生成成功: " . json_encode($strategy, JSON_UNESCAPED_UNICODE));
            
            return json([
                'success' => true,
                'data' => $strategy
            ]);

        } catch (\Exception $e) {
            error_log('生成用户结算策略失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '生成结算策略失败']);
        }
    }

    /**
     * 生成房间整体净结算策略
     */
    public function generateRoomStrategy(Request $request): Response
    {
        $roomId = $request->get('room_id');
        
        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            $strategy = SettlementStrategyService::generateRoomSettlementStrategy($roomId);
            
            return json([
                'success' => true,
                'data' => $strategy
            ]);

        } catch (\Exception $e) {
            error_log('生成房间结算策略失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '生成结算策略失败']);
        }
    }

    /**
     * 保存净结算策略到数据库
     */
    public function saveSettlementStrategy(Request $request): Response
    {
        $roomId = $request->get('room_id');
        $settlementType = $request->get('settlement_type', 'manual');
        $settlementReason = $request->get('settlement_reason', '用户生成结算策略');
        
        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            // 生成房间结算策略
            $strategy = SettlementStrategyService::generateRoomSettlementStrategy($roomId);
            
            if ($strategy['strategy'] === 'error') {
                return json(['success' => false, 'message' => $strategy['message']]);
            }

            // 创建房间结算记录
            $settlement = RoomSettlement::createSettlement($roomId, $settlementType, $settlementReason);
            
            return json([
                'success' => true,
                'message' => '净结算策略已保存',
                'data' => [
                    'settlement_id' => $settlement->id,
                    'strategy' => $strategy
                ]
            ]);

        } catch (\Exception $e) {
            error_log('保存结算策略失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '保存结算策略失败']);
        }
    }

    /**
     * 生成最优结算策略（考虑茶饭费）
     */
    public function generateOptimalStrategy(Request $request): Response
    {
        $roomId = $request->get('room_id');
        
        if (!$roomId) {
            return json(['success' => false, 'message' => '房间ID不能为空']);
        }

        try {
            $strategy = SettlementStrategyService::generateOptimalSettlementWithTeaMeal($roomId);
            
            return json([
                'success' => true,
                'data' => $strategy
            ]);

        } catch (\Exception $e) {
            error_log('生成最优结算策略失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '生成最优结算策略失败']);
        }
    }

    /**
     * 获取用户的历史结算策略
     */
    public function getUserSettlementHistory(Request $request): Response
    {
        $userId = $request->get('user_id');
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 20);
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            // 获取用户参与的所有结算记录
            $settlements = RoomSettlement::whereJsonContains('players_data', [['user_id' => $userId]])
                ->orderBy('settlement_time', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            $history = [];
            foreach ($settlements as $settlement) {
                // 从 players_data 中找到当前用户的数据
                $userData = null;
                if ($settlement->players_data) {
                    foreach ($settlement->players_data as $player) {
                        if ($player['user_id'] == $userId) {
                            $userData = $player;
                            break;
                        }
                    }
                }

                if (!$userData) continue;

                $history[] = [
                    'settlement_id' => $settlement->id,
                    'room_code' => $settlement->room_code,
                    'room_name' => $settlement->room_name,
                    'settlement_time' => $settlement->settlement_time->format('Y-m-d H:i:s'),
                    'user_final_score' => $userData['final_score'],
                    'is_winner' => $userData['is_winner'],
                    'settlement_type' => $settlement->settlement_type,
                    'settlement_reason' => $settlement->settlement_reason
                ];
            }

            return json([
                'success' => true,
                'data' => [
                    'history' => $history,
                    'pagination' => [
                        'current_page' => $settlements->currentPage(),
                        'total_pages' => $settlements->lastPage(),
                        'total_items' => $settlements->total(),
                        'per_page' => $settlements->perPage(),
                        'has_more' => $settlements->hasMorePages()
                    ]
                ]
            ]);

        } catch (\Exception $e) {
            error_log('获取用户结算历史失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '获取结算历史失败']);
        }
    }

    /**
     * 保存用户结算策略
     */
    public function saveUserSettlementStrategy(Request $request): Response
    {
        $userId = $request->get('user_id');
        $roomId = $request->get('room_id');
        $strategy = $request->get('strategy');
        
        if (!$userId || !$roomId || !$strategy) {
            return json(['success' => false, 'message' => '用户ID、房间ID和策略数据不能为空']);
        }

        try {
            error_log("保存用户结算策略: user_id={$userId}, room_id={$roomId}");
            
            // 检查房间状态
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }
            
            if ($room->status === 'finished') {
                return json(['success' => false, 'message' => '房间已结算，无法保存结算策略']);
            }
            
            // 检查用户在房间中的状态
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();
                
            if (!$roomUser) {
                return json(['success' => false, 'message' => '用户不在该房间中']);
            }
            
            if ($roomUser->status === \app\model\RoomUser::STATUS_FINISHED) {
                return json(['success' => false, 'message' => '您在该房间的结算已完成，无法保存结算策略']);
            }
            
            // 保存用户结算策略
            $detail = \app\model\RoomSettlementDetail::saveUserSettlementStrategy($userId, $roomId, $strategy);
            
            // 检查是否所有用户都已生成策略
            $allUsersGenerated = \app\model\RoomSettlementDetail::allUsersGeneratedStrategy($roomId);
            $generatedCount = \app\model\RoomSettlementDetail::getRoomGeneratedStrategyCount($roomId);
            $totalCount = \app\model\RoomSettlementDetail::getRoomTotalUserCount($roomId);
            
            error_log("策略生成状态: 已生成={$generatedCount}, 总数={$totalCount}, 全部完成={$allUsersGenerated}");
            
            // 如果所有人都生成了策略，自动触发最终结算
            if ($allUsersGenerated) {
                try {
                    error_log("所有人已生成策略，开始自动结算: room_id={$roomId}");
                    
                    // 创建正式结算记录
                    $settlement = \app\model\RoomSettlement::createSettlement($roomId, 'auto', '所有人已生成结算策略，自动结算');
                    
                    // 更新房间状态为finished
                    $room->status = 'finished';
                    $room->current_players = 0;
                    $room->save();
                    
                    // 更新所有房间用户状态为finished
                    \app\model\RoomUser::where('room_id', $roomId)
                        ->whereIn('status', [\app\model\RoomUser::STATUS_ACTIVE, \app\model\RoomUser::STATUS_LEFT])
                        ->update([
                            'status' => \app\model\RoomUser::STATUS_FINISHED,
                            'left_at' => date('Y-m-d H:i:s')
                        ]);
                    
                    // 更新所有记账记录为已结算
                    \app\model\AccountingRecord::where('room_id', $roomId)
                        ->update(['is_settled' => 1]);
                    
                    // 发送WebSocket通知
                    try {
                        $websocketService = \app\service\WebSocketService::getInstance();
                        $websocketService->sendRoomSettlementMessage($roomId, [
                            'message' => '所有人已生成结算策略，房间自动结算完成',
                            'settlement_id' => $settlement->id,
                            'settlement_time' => date('Y-m-d H:i:s'),
                            'auto_navigate' => true,
                            'navigate_url' => '/pages/room-settlement/room-settlement?settlement_id=' . $settlement->id
                        ]);
                    } catch (\Exception $wsException) {
                        error_log('发送自动结算WebSocket消息失败: ' . $wsException->getMessage());
                    }
                    
                    error_log("自动结算完成: room_id={$roomId}, settlement_id={$settlement->id}");
                    
                } catch (\Exception $settlementException) {
                    error_log('自动结算失败: ' . $settlementException->getMessage());
                    // 结算失败不影响策略保存
                }
            }
            
            return json([
                'success' => true,
                'message' => $allUsersGenerated ? '结算策略保存成功，房间已自动结算' : '结算策略保存成功',
                'data' => [
                    'detail_id' => $detail->id,
                    'user_id' => $userId,
                    'room_id' => $roomId,
                    'all_users_generated' => $allUsersGenerated,
                    'generated_count' => $generatedCount,
                    'total_count' => $totalCount,
                    'can_finalize_settlement' => $allUsersGenerated,
                    'auto_settled' => $allUsersGenerated
                ]
            ]);

        } catch (\Exception $e) {
            error_log('保存用户结算策略失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '保存结算策略失败']);
        }
    }

    /**
     * 最终确认结算（最后一个用户确认后）
     */
    public function finalizeSettlement(Request $request): Response
    {
        $roomId = $request->get('room_id');
        $userId = $request->get('user_id');
        
        if (!$roomId || !$userId) {
            return json(['success' => false, 'message' => '房间ID和用户ID不能为空']);
        }

        try {
            error_log("最终确认结算: room_id={$roomId}, user_id={$userId}");
            
            // 检查房间状态
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                return json(['success' => false, 'message' => '房间不存在']);
            }
            
            if ($room->status === 'finished') {
                return json(['success' => false, 'message' => '房间已结算，无法重复确认']);
            }
            
            // 检查用户在房间中的状态
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();
                
            if (!$roomUser) {
                return json(['success' => false, 'message' => '用户不在该房间中']);
            }
            
            if ($roomUser->status === \app\model\RoomUser::STATUS_FINISHED) {
                return json(['success' => false, 'message' => '您在该房间的结算已完成，无法重复确认']);
            }
            
            // 检查是否所有用户都已生成策略
            if (!\app\model\RoomSettlementDetail::allUsersGeneratedStrategy($roomId)) {
                return json(['success' => false, 'message' => '还有用户未生成结算策略，无法确认结算']);
            }
            
            // 创建正式结算记录
            $settlement = \app\model\RoomSettlement::createSettlement($roomId, 'manual', '用户确认结算');
            
            // 更新房间状态为finished
            $room->status = 'finished';
            $room->current_players = 0;
            $room->save();
            
            error_log("房间状态已更新为finished: room_id={$roomId}");
            
            // 更新所有房间用户状态为finished
            \app\model\RoomUser::where('room_id', $roomId)
                ->whereIn('status', [\app\model\RoomUser::STATUS_ACTIVE, \app\model\RoomUser::STATUS_LEFT])
                ->update([
                    'status' => \app\model\RoomUser::STATUS_FINISHED,
                    'left_at' => \Carbon\Carbon::now()
                ]);
                
            error_log("所有房间用户状态已更新为finished");
            
            return json([
                'success' => true,
                'message' => '结算确认成功，房间已结束',
                'data' => [
                    'settlement_id' => $settlement->id,
                    'room_id' => $roomId,
                    'room_status' => 'finished',
                    'settlement_time' => $settlement->settlement_time->format('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Exception $e) {
            error_log('最终确认结算失败: ' . $e->getMessage());
            return json(['success' => false, 'message' => '确认结算失败']);
        }
    }
}
